package org.dreamwork.jasmine2.restful.client.gui.util;

import org.apache.log4j.Logger;
import org.dreamwork.misc.Base64;
import org.dreamwork.secure.SecureContext;
import org.dreamwork.util.StringUtil;

import java.io.*;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2014/12/11
 * Time: 14:20
 */
public class KeyUtil {
    private static PublicKey key;
    private static SecureContext context;

    private static final Logger logger = Logger.getLogger (KeyUtil.class);

    public static void setPublicKey (PublicKey key) {
        KeyUtil.key = key;
    }

    public static PublicKey getPublicKey () {
        return key;
    }

    public static SecureContext getContext () {
        return context;
    }

    public static void setContext (SecureContext context) {
        KeyUtil.context = context;
    }

    public static void loadKey (File file) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        if (logger.isDebugEnabled ())
            logger.debug ("trying load public key from " + file.getCanonicalPath ());
        FileReader fr = new FileReader (file);
        try {
            BufferedReader reader = new BufferedReader (fr);
            String line;
            StringBuilder builder = new StringBuilder ();
            while ((line = reader.readLine ()) != null) {
                if (line.startsWith ("--")) continue;
                if (StringUtil.isEmpty (line)) continue;
                builder.append (line.trim ());
            }
            byte[] buff = builder.toString ().getBytes ();
            buff = Base64.decode (buff);

            X509EncodedKeySpec spec = new X509EncodedKeySpec (buff);
            KeyFactory factory = KeyFactory.getInstance ("rsa");
            key = factory.generatePublic (spec);
            if (logger.isDebugEnabled ())
                logger.debug ("public key load as " + key);
        } finally {
            fr.close ();
        }
    }
}